package com.link_with_health.service.impl;

import com.link_with_health.exception.AuthenticationFailedException;
import com.link_with_health.exception.BaseException;
import com.link_with_health.exception.ModifyDatabaseFailedException;
import com.link_with_health.exception.NullQueryResultException;
import com.link_with_health.mapper.UserMapper;
import com.link_with_health.mapper.UserStatusMapper;
import com.link_with_health.model.UserEntity;
import com.link_with_health.model.UserStatusEntity;
import com.link_with_health.service.BaseService;
import com.link_with_health.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service("userService")
public class UserServiceImpl extends BaseService implements UserService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    UserMapper userMapper;
    @Resource
    UserStatusMapper userStatusMapper;


    // 封禁----3
    // 删除----4
    // 禁用----6
    private static final int[] NO_ACCESS_STATUS = {3,4,6};

    /**
     * 通过用户id获取用户信息
     * @param userId 用户id
     * @return 用户信息
     * @throws BaseException 异常
     */
    @Override
    public UserEntity getUserByUserId(Long userId) throws BaseException {
        UserEntity entity = null;
        try{
            entity = userMapper.getUserByUserId(userId);
        }catch (Exception e){
            logger.error("[query user by user.user_id failed]",e);
        }
        if(entity == null)
            throw new NullQueryResultException("USER.USER_ID: "+userId);

        return entity;
    }

    /**
     * 通过用户名字获取用户信息
     * @param  username 用户名字
     * @return 用户信息
     * @throws BaseException 异常
     */
    @Override
    public UserEntity getUserByUsername(String username) throws BaseException{
        UserEntity entity = null;
        try{
            entity = userMapper.getUserByUsername(username);
        }catch (Exception e){
            logger.error("[query user by email failed]",e);
        }
        if(entity == null)
            throw new NullQueryResultException("USER.USER_NAME:" + username);

        return entity;
    }

    /**
     * 通过邮箱获取用户信息
     * @param email 邮箱信息
     * @return 用户信息
     * @throws BaseException 异常
     */
    @Override
    public UserEntity getUserByEmail(String email) throws BaseException{
        UserEntity entity = null;
        try{
            entity = userMapper.getUserByEmail(email);
        }catch (Exception e){
            logger.error("[query user by email failed]",e);
        }
        if(entity == null)
            throw new NullQueryResultException("USER.EMAIL:" + email);

        return entity;
    }

    /**
     * 获取对应状态的所有用户
     * @param status 用户状态
     * @return 用户信息
     */
    @Override
    public List<UserEntity> getUserByStatus(int status) throws BaseException{
        List<UserEntity> userList = null;
        try{
            userList = userMapper.getUsersByStatus(status);
        }catch (Exception e){
            logger.error("[query user by email failed]",e);
        }
        if(userList == null || userList.isEmpty())
            throw new NullQueryResultException("USER.USER_STATUS: "+status);
        return userList;
    }

    /**
     * 通过手机信息获取用户信息
     * @param phone 手机号码
     * @return 用户信息
     * @throws BaseException 异常
     */
    @Override
    public UserEntity getUserByPhone(String phone) throws BaseException{
        UserEntity entity = null;
        try{
            entity = userMapper.getUserByTelephone(phone);
        }catch (Exception e){
            logger.error("[query user by email failed]",e);
        }
        if(entity == null)
            throw new NullQueryResultException("USER.TELEPHONE: " + phone);

        return entity;
    }

    /**
     * 获取所有用户信息
     * @return 用户信息
     */
    @Override
    public List<UserEntity> getAllUsers() throws BaseException{
        List<UserEntity> allUsers = null;
        try{
            allUsers = userMapper.getAllUsers();
        }catch (Exception e) {
            logger.error("[get all user failed]",e);
        }
        if(allUsers == null || allUsers.isEmpty()){
            throw new NullQueryResultException("ALL USERS");
        }
        return allUsers;
    }

    /**
     * 添加用户信息
     * @param user 用户信息
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int addUser(UserEntity user) throws BaseException{
        int result = 0;
        try {
           // if(isValidEmail(user.getEmail()) && isValidPhone(user.getTelephone()))
                result = userMapper.userReignByBaseInfo(user);

        } catch (Exception e) {
            logger.error("[add user failed]",e);
        }
        if(result == 0)
            throw new ModifyDatabaseFailedException("INSERT USER FAILED "+ user.toString());
        return result;
    }

    /**
     * 更改用户信息
     * @param user 用户信息
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int changeUser(UserEntity user) throws BaseException{
        int result = 0;
        try {
            if(isValidEmail(user.getEmail()) && isValidPhone(user.getTelephone()))
                result = userMapper.updateUserInfo(user);

        } catch (Exception e) {
            logger.error("[change user failed]",e);
        }
        if(result == 0)
            throw new ModifyDatabaseFailedException("UPDATE USER FAILED "+ user.toString());
        return result;
    }

    /**
     * 删除用户
     * @param user 用户信息
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int deleteUser(UserEntity user) throws BaseException{
        int result = 0;
        try {
            result = userMapper.deleteUserInfo(user.getUserId());

        } catch (Exception e) {
            logger.error("[delete user failed]",e);
        }
        if(result == 0)
            throw new ModifyDatabaseFailedException("DELETE USER FAILED "+ user.toString());
        return result;
    }

    /**
     * 通过用户状态id查找状态信息
     * @param id 用户状态信息
     * @return 状态信息
     * @throws BaseException 异常
     */
    @Override
    public UserStatusEntity getUserStatusById(Integer id) throws BaseException{
        UserStatusEntity entity = null;
        try{
            entity = userStatusMapper.queryUserStatusById(id);
        }catch (Exception e){
            logger.error("[query userStatus by userStatus.id failed]",e);
        }
        if(entity == null)
            throw new NullQueryResultException("USERSTATUS.ID: "+id);
        return entity;
    }

    /**
     * 通过用户id获取用户状态
     * @param userId 用户id
     * @return 状态信息
     * @throws BaseException 异常
     */
    @Override
    public UserStatusEntity getUserStatusByUser(Long userId) throws BaseException{
        UserStatusEntity entity = null;
        try{
            entity = userStatusMapper.queryUserStatusByUser(userId);
        }catch (Exception e){
            logger.error("[query userStatus by userStatus.id failed]",e);
        }
        if(entity == null)
            throw new NullQueryResultException("USERSTATUS.ID: "+userId);
        return entity;
    }

    /**
     * 获取所有状态
     * @return 状态信息
     * @throws BaseException 异常
     */
    @Override
    public List<UserStatusEntity> getAllUserStatus() throws BaseException{
        List<UserStatusEntity> statusList = null;
        try{
            statusList = userStatusMapper.queryAllUserStatus();
        }catch (Exception e){
            logger.error("[query userStatus by userStatus.id failed]",e);
        }
        if(statusList == null || statusList.isEmpty())
            throw new NullQueryResultException("ALL USERSTATUS");
        return statusList;
    }

    /**
     * 添加状态信息
     * @param status 状态信息
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int addUserStatus(UserStatusEntity status) throws BaseException{
        int result = 0;
        try {
            result = userStatusMapper.insertUserStatus(status);

        } catch (Exception e) {
            logger.error("[add userStatus failed]",e);
        }
        if(result == 0)
            throw new ModifyDatabaseFailedException("INSERT USERSTATUS FAILED "+ status.toString());
        return result;
    }

    /**
     * 改动状态信息
     * @param status 状态信息
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int changeUserStatus(UserStatusEntity status) throws BaseException{
        int result = 0;
        try {
            result = userStatusMapper.updateUserStatus(status);

        } catch (Exception e) {
            logger.error("[change userStatus failed]",e);
        }
        if(result == 0)
            throw new ModifyDatabaseFailedException("UPDATE USERSTATUS FAILED "+ status.toString());
        return result;
    }

    /**
     * 删除状态信息
     * 当有用户处于该状态时 无法删除状态信息
     * @param statusId  状态id
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int deleteAdminUserById(int statusId) throws BaseException{
        int result = 0;
        try {
            if(this.getUserByStatus(statusId) == null)
                result = userStatusMapper.deleteUserStatus(statusId);
        } catch (Exception e) {
            logger.error("[delete userStatus failed]",e);
        }
        if (result == 0){
            throw new ModifyDatabaseFailedException("DELETE USERSTATUS FAILED "+ statusId);
        }

        return result;
    }

    /**
     * 查看该状态信息是否可以访问
     * @param status 状态信息
     * @return 判断结果
     */
    @Override
    public boolean isInvalidStatus(int status){
        for (int element : NO_ACCESS_STATUS){
            if(element == status)
                return true;
        }
        return false;
    }

    /**
     * 手机检验
     * @param phone 手机号码
     * @return 检验结果
     */
    private boolean isValidPhone(String phone){
        return regexUtil.isEmpty(phone) || regexUtil.isPhone(phone);
    }

    /**
     * 邮箱校验
     * @param email 邮箱结果
     * @return 检验结果
     */
    private boolean isValidEmail(String email){
        return regexUtil.isEmpty(email) || regexUtil.isEmail(email);
    }
}
